﻿using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WebControls;

namespace SPUserPermissionCheck.SPUserPermissionCheck
{
    public partial class SPUserPermissionCheckUserControl : UserControl
    {
        public static string userName = "";
        public static string strUserToCheck = "";
        public string percorsoFile = "";
        public ArrayList arrLstGroupToCheck = new ArrayList();

        string corpoTxtBox = "";

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Page.IsPostBack)
            {
                lblError.Text = "";
            }

        }

        public long TraverseFolder(SPFolder folder)
        {

            // Begin recursive function
            

            long lFolderSize = 0;
            string dirittiUser = "";

            try
            {

                foreach (SPFolder subfolder in folder.SubFolders)
                {
                    if (!subfolder.Name.Contains("Forms") && !folder.Name.Contains("Forms"))
                    {

                        //corpoTxtBox += subfolder.Name ;


                        //Get roles assigned for each list
                        foreach (SPRoleAssignment assignedRoles in subfolder.Item.RoleAssignments)
                        {
                            //Check whether the role if for a user
                            if (assignedRoles.Member is SPUser)
                            {
                                //get the user from the role
                                SPUser user = (SPUser)assignedRoles.Member;
                                //Check whether its the same user that is entered
                                if (user.LoginName.Equals(strUserToCheck, StringComparison.OrdinalIgnoreCase))
                                {

                                    //Get users permissions - Add Remove Etc
                                    foreach (SPRoleDefinition item in assignedRoles.RoleDefinitionBindings)
                                    {

                                        if (item.Name != "Limited Access")
                                        {
                                            dirittiUser += item.Name + ",";
                                        }

                                    }

                                }
                            }
                            else
                            {

                                if (assignedRoles.Member is SPGroup)
                                {
                                    //get the user from the role
                                    SPGroup group = (SPGroup)assignedRoles.Member;
                                    //Check whether its the same user that is entered
                                    foreach (string strGroupToCheck in arrLstGroupToCheck)
                                    {

                                        if (group.LoginName.Equals(strGroupToCheck, StringComparison.OrdinalIgnoreCase))
                                        {

                                            //Get users permissions - Add Remove Etc
                                            foreach (SPRoleDefinition item in assignedRoles.RoleDefinitionBindings)
                                            {

                                                if (item.Name != "Limited Access")
                                                {
                                                    dirittiUser += item.Name + ",";
                                                }

                                            }
                                        }

                                    }
                                }

                            }

                        }


                        if (dirittiUser.ToString() != "" && dirittiUser.ToString() != "Limited Access,")
                        {
                            txtDocLibrary.Text += Environment.NewLine + corpoTxtBox + subfolder.Url.Replace("/", " > ") + " ... " + dirittiUser.ToString() + Environment.NewLine;
                            corpoTxtBox = "";
                            dirittiUser = "";
                            //txtDocLibrary.Text += Environment.NewLine;
                        }
                        else
                        {
                            dirittiUser = "";
                        }


                        if (chkFiles.Checked == true)
                        {
                            percorsoFile = subfolder.Url.ToString();
                            GetItems(subfolder);
                        }
                        else
                        {
                            //txtDocLibrary.Text += Environment.NewLine;
                            percorsoFile = "";
                        }

                        TraverseFolder(subfolder);//RootNode

                    }

                }

            }

            catch (Exception e)
            {

                Console.WriteLine(e.Message);

            }

            return lFolderSize;

        }


        ///check permissions on document libraries items
        public long GetItems(SPFolder subfolder)
        {

            long lFolderSize = 0;
            string dirittiFileUser = "";

            foreach (SPFile file in subfolder.Files)
            {

                foreach (SPRoleAssignment assignedFileRoles in file.Item.RoleAssignments)
                {

                    //Check whether the role if for a user
                    if (assignedFileRoles.Member is SPUser)
                    {
                        //get the user from the role
                        SPUser user = (SPUser)assignedFileRoles.Member;
                        //Check whether its the same user that is entered
                        if (user.LoginName.Equals(strUserToCheck, StringComparison.OrdinalIgnoreCase))
                        {

                            //Get users permissions - Add Remove Etc
                            foreach (SPRoleDefinition itemFile in assignedFileRoles.RoleDefinitionBindings)
                            {
                                if (itemFile.Name != "Limited Access")
                                {
                                    dirittiFileUser += itemFile.Name + ",";
                                }

                            }

                        }
                    }
                    else
                    {

                        if (assignedFileRoles.Member is SPGroup)
                        {
                            //get the user from the role
                            SPGroup group = (SPGroup)assignedFileRoles.Member;
                            //Check whether its the same user that is entered
                            foreach (string strGroupToCheck in arrLstGroupToCheck)
                            {

                                if (group.LoginName.Equals(strGroupToCheck, StringComparison.OrdinalIgnoreCase))
                                {

                                    //Get users permissions - Add Remove Etc
                                    foreach (SPRoleDefinition itemFile in assignedFileRoles.RoleDefinitionBindings)
                                    {
                                        if (itemFile.Name != "Limited Access")
                                        {
                                            dirittiFileUser += itemFile.Name + ",";
                                        }

                                    }

                                }

                            }
                        }

                    }

                }

                if (dirittiFileUser.ToString() != "" && dirittiFileUser.ToString() != "Limited Access,")
                {
                    if (percorsoFile == subfolder.Url.ToString())
                    {
                        txtDocLibrary.Text += "    " + file.Name + " ... " + dirittiFileUser.ToString() + Environment.NewLine;

                    }
                    else
                    {
                        txtDocLibrary.Text += Environment.NewLine + corpoTxtBox + subfolder.Url.Replace("/", " > ") + Environment.NewLine;
                        txtDocLibrary.Text += "    " + file.Name + " ... " + dirittiFileUser.ToString() + Environment.NewLine;
                    }

                    percorsoFile = subfolder.Url.ToString();
                    corpoTxtBox = "";
                    dirittiFileUser = "";
                }
                else
                {
                    dirittiFileUser = "";
                }

            }

            return lFolderSize;
        }


        //check permissions on list's items
        public long GetListItems(SPList listMadre)//, TreeNode nodeFile)
        {
            long lFolderSize = 0;
            string dirittiFileUser = "";

            foreach (SPListItem itemFiglio in listMadre.Items)
            {

                corpoTxtBox += "> " + itemFiglio.Title + " ... ";


                foreach (SPRoleAssignment assignedFileRoles in itemFiglio.RoleAssignments)
                {
                    //Check whether the role if for a user
                    if (assignedFileRoles.Member is SPUser)
                    {
                        //get the user from the role
                        SPUser user = (SPUser)assignedFileRoles.Member;
                        //Check whether its the same user that is entered
                        if (user.LoginName.Equals(strUserToCheck, StringComparison.OrdinalIgnoreCase))
                        {

                            //Get users permissions - Add Remove Etc
                            foreach (SPRoleDefinition itemFile in assignedFileRoles.RoleDefinitionBindings)
                            {
                                if (itemFile.Name != "Limited Access")
                                {
                                    dirittiFileUser += itemFile.Name + ",";
                                    corpoTxtBox += itemFile.Name + ",";
                                }
                            }

                        }
                    }
                    else
                    {

                        if (assignedFileRoles.Member is SPGroup)
                        {
                            //get the user from the role
                            SPGroup group = (SPGroup)assignedFileRoles.Member;
                            //Check whether its the same user that is entered
                            foreach (string strGroupToCheck in arrLstGroupToCheck)
                            {

                                if (group.LoginName.Equals(strGroupToCheck, StringComparison.OrdinalIgnoreCase))
                                {

                                    //Get users permissions - Add Remove Etc
                                    foreach (SPRoleDefinition itemFile in assignedFileRoles.RoleDefinitionBindings)
                                    {
                                        if (itemFile.Name != "Limited Access")
                                        {
                                            dirittiFileUser += itemFile.Name + ",";
                                            corpoTxtBox += itemFile.Name + ",";
                                        }

                                    }

                                }

                            }
                        }

                    }

                }

                if (dirittiFileUser.ToString() == "" || dirittiFileUser.ToString() == "Limited Access,")
                {
                    corpoTxtBox = "";
                }
                else
                {
                    txtDocLibrary.Text += corpoTxtBox + Environment.NewLine;
                    corpoTxtBox = "";
                }

                dirittiFileUser = "";

            }

            return lFolderSize;
        }


        protected void Button1_Click(object sender, EventArgs e)
        {

            //Check if user is in people picker correctly
            
            if (Owner.ResolvedEntities.Count > 0)
            {

                PickerEntity selectedEntity = (PickerEntity)Owner.ResolvedEntities[0];

                strUserToCheck = selectedEntity.Key.ToString();
            }
            else
            {
                return;
            }

            //Setup the output
            txtDocLibrary.Text = "KT - User permission check" + Environment.NewLine;
            txtDocLibrary.Text += Environment.NewLine;

            if (chkFiles.Checked == true)
            {
                txtDocLibrary.Text += "Permissions on folders and documents for: " + SPContext.Current.Web.Title.ToString() + Environment.NewLine;
            }
            else
            {
                txtDocLibrary.Text += "Permissions on folders for: " + SPContext.Current.Web.Title.ToString() + Environment.NewLine;
            }

            txtDocLibrary.Text += Environment.NewLine;
            txtDocLibrary.Text += "User: " + strUserToCheck.ToString() + Environment.NewLine;
            txtDocLibrary.Text += Environment.NewLine;
            txtDocLibrary.Text += "Elaborated on: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + " by " + SPContext.Current.Web.CurrentUser.LoginName.ToString() + Environment.NewLine;
            txtDocLibrary.Text += Environment.NewLine;
            txtDocLibrary.Text += Environment.NewLine;
            //txtDocLibrary.Text += Environment.NewLine;


            string dirittiUser = "";
            corpoTxtBox = "";

            SPUserToken AdminUserToken = new SPSite(SPContext.Current.Web.Url).SystemAccount.UserToken;

            //SharePoint connection
            using (SPSite oSite = new SPSite(SPContext.Current.Web.Url, AdminUserToken))
            {

                using (SPWeb oWeb = oSite.OpenWeb())
                {

                    if (oWeb.DoesUserHavePermissions(strUserToCheck, SPBasePermissions.Open) == false)
                    {
                        lblError.Text = "Selected user have no permissions";
                        return;
                    }

                    SPUser oUser = oWeb.AllUsers[strUserToCheck];

                    SPGroupCollection userGroups = oUser.Groups;

                    //If user is in more groups, put in a array
                    foreach (SPGroup oGroup in userGroups)
                    {
                        arrLstGroupToCheck.Add(oGroup.Name);
                    }

                    //********************************************************

                    //Lists are excluded from check
                    //Code is ready but commented

                    //Read lists in LISTS
                    //foreach (SPList list in oWeb.Lists)
                    //{

                    //    //system's lists are excluded 
                    //    if (list.Hidden == false && (!list.RootFolder.Name.Equals("Application Log") && !list.RootFolder.Name.Equals("Reports List") && !list.RootFolder.Name.Equals("Templates")))
                    //    {
                    //        if (list.BaseType == SPBaseType.GenericList)
                    //        {

                    //            corpoTxtBox = "---- List :" + list.Title + " ... ";

                    //            //Get roles assigned for each list
                    //            foreach (SPRoleAssignment assignedRoles in list.RoleAssignments)
                    //            {
                    //                //Check whether the role if for a user
                    //                if (assignedRoles.Member is SPUser)
                    //                {
                    //                    //get the user from the role
                    //                    SPUser user = (SPUser)assignedRoles.Member;
                    //                    //Check whether its the same user that is entered
                    //                    if (user.LoginName.Equals(strUserToCheck, StringComparison.OrdinalIgnoreCase))
                    //                    {

                    //                        //Get users permissions - Add Remove Etc
                    //                        foreach (SPRoleDefinition item in assignedRoles.RoleDefinitionBindings)
                    //                        {
                    //                            if (item.Name != "Limited Access")
                    //                            {
                    //                                dirittiUser += item.Name + ",";
                    //                                corpoTxtBox += item.Name + ",";
                    //                            }
                    //                        }
                    //                    }
                    //                }
                    //                else
                    //                {
                    //                    if (assignedRoles.Member is SPGroup)
                    //                    {
                    //                        //get the user from the role
                    //                        SPGroup group = (SPGroup)assignedRoles.Member;
                    //                        //Check whether its the same user that is entered
                    //                        foreach (string strGroupToCheck in arrLstGroupToCheck)
                    //                        {

                    //                            if (group.LoginName.Equals(strGroupToCheck, StringComparison.OrdinalIgnoreCase))
                    //                            {

                    //                                //Get users permissions - Add Remove Etc
                    //                                foreach (SPRoleDefinition item in assignedRoles.RoleDefinitionBindings)
                    //                                {
                    //                                    if (item.Name != "Limited Access")
                    //                                    {
                    //                                        dirittiUser += item.Name + ",";
                    //                                        corpoTxtBox += item.Name + ",";
                    //                                    }
                    //                                }

                    //                            }

                    //                        }
                    //                    }

                    //                }

                    //            }


                    //            //Call function for read items in list
                    //            if (chkFiles.Checked == true)
                    //            {

                    //                if (dirittiUser.ToString() != "" && dirittiUser.ToString() != "Limited Access,")
                    //                {
                    //                    txtDocLibrary.Text += corpoTxtBox + Environment.NewLine;
                    //                    corpoTxtBox = "";
                    //                    dirittiUser = "";
                    //                }
                    //                else
                    //                {
                    //                    corpoTxtBox += "\r\n";
                    //                    dirittiUser = "";
                    //                }
                    //                GetListItems(list);//, nodeList);
                    //            }
                    //            else
                    //            {
                    //                if (dirittiUser.ToString() == "" || dirittiUser.ToString() == "Limited Access,")
                    //                {
                    //                    corpoTxtBox = "";
                    //                    dirittiUser = "";
                    //                }


                    //                if (corpoTxtBox.ToString() != "")
                    //                {
                    //                    txtDocLibrary.Text += corpoTxtBox + Environment.NewLine;
                    //                    corpoTxtBox = "";
                    //                    dirittiUser = "";
                    //                }

                    //            }

                    //        }


                    //    }

                    //}


                    //********************************************************
                    //Read folders in Document Libraries

                    //dirittiUser = "";
                    //corpoTxtBox = "";
                    //txtDocLibrary.Text += Environment.NewLine;

                    foreach (SPList list in oWeb.Lists)
                    {
                        //System's lists are excluded

                        //**********************   
                        if (list.Hidden == false && (!list.RootFolder.Name.Equals("AnalyticsReports") && !list.RootFolder.Name.Equals("FormServerTemplates") && !list.RootFolder.Name.Equals("SiteCollectionDocuments") && !list.RootFolder.Name.Equals("SiteCollectionImages") && !list.RootFolder.Name.Equals("Style Library")))
                        {
                            //Read only the lists in documents libraries
                            if (list.BaseType == SPBaseType.DocumentLibrary)
                            {

                                corpoTxtBox = "---- Document library: " + list.Title;


                                //Get roles assigned for each list
                                foreach (SPRoleAssignment assignedRoles in list.RoleAssignments)
                                {
                                    //Check whether the role if for a user
                                    if (assignedRoles.Member is SPUser)
                                    {
                                        //get the user from the role
                                        SPUser user = (SPUser)assignedRoles.Member;
                                        //Check whether its the same user that is entered
                                        if (user.LoginName.Equals(strUserToCheck, StringComparison.OrdinalIgnoreCase))
                                        {


                                            //Get users permissions - Add Remove Etc
                                            foreach (SPRoleDefinition item in assignedRoles.RoleDefinitionBindings)
                                            {
                                                if (item.Name != "Limited Access")
                                                {
                                                    dirittiUser += item.Name + ",";
                                                }

                                            }

                                        }
                                    }
                                    else
                                    {
                                        if (assignedRoles.Member is SPGroup)
                                        {
                                            //get the user from the role
                                            SPGroup group = (SPGroup)assignedRoles.Member;
                                            //Check whether its the same user that is entered
                                            foreach (string strGroupToCheck in arrLstGroupToCheck)
                                            {

                                                if (group.LoginName.Equals(strGroupToCheck, StringComparison.OrdinalIgnoreCase))
                                                {

                                                    //Get users permissions - Add Remove Etc
                                                    foreach (SPRoleDefinition item in assignedRoles.RoleDefinitionBindings)
                                                    {
                                                        if (item.Name != "Limited Access")
                                                        {
                                                            dirittiUser += item.Name + ",";
                                                        }

                                                    }

                                                }

                                            }
                                        }

                                    }
                                }


                                //Call the recursive function for read folders inside Document Libraries

                                if (dirittiUser.ToString() != "" && dirittiUser.ToString() != "Limited Access,")
                                {
                                    txtDocLibrary.Text += Environment.NewLine + corpoTxtBox + " ... " + dirittiUser.ToString() + Environment.NewLine;
                                    corpoTxtBox = "";
                                    dirittiUser = "";
                                }
                                else
                                {
                                    corpoTxtBox += "\r\n";
                                    dirittiUser = "";
                                }

                                if (chkFiles.Checked == true)
                                {
                                    GetItems(list.RootFolder);
                                }


                                
                                TraverseFolder(list.RootFolder);

                            }
                        }

                    }


                }
            }


        }


    }

}
